from tortoise.expressions import Q
from tortoise.functions import Sum

from app.controllers.goods.goods import goods_controller
from app.core.crud import CRUDBase
from app.models import Goods, CustomerUser
from app.models.saas import PerformancePercentage
from app.schemas.saas import PerformancePercentageCreate, PerformancePercentageUpdate


class PerformancePercentageController(CRUDBase[PerformancePercentage, PerformancePercentageCreate, PerformancePercentageUpdate]):
    def __init__(self):
        super().__init__(model=PerformancePercentage)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict(exclude_fields=["updated_at","deleted_at"]) for obj in objs]
        return total, data

    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_create(self, obj_in: PerformancePercentageCreate):
        await self.create(obj_in=obj_in)
        return True

    async def do_update(self, obj_in: PerformancePercentageUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_delete(self, data_id: int):
        await self.remove(id=data_id)
        return True

    async def do_total_yeji(self,search: Q = Q()):
        query = self.model.filter(search)
        count = await query.count()
        data = await query.annotate(total=Sum("price")).first().values("total")
        return count,data

    async def do_yeji(self,page: int, page_size: int,search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs = await query.offset((page - 1) * page_size).limit(page_size).order_by("-id")
        data = [await obj.to_dict() for obj in objs]
        for obj in data:
            goods_data = await Goods.filter(id=obj['goods_id']).first().values()
            customer_data =await CustomerUser.filter(id=obj['user_id']).first().values()
            obj['project_name'] =goods_data['name']
            obj['receive_name'] = customer_data['name']
        return total, data



performance_percentage_controller = PerformancePercentageController()
